package com.example.wyh.intelcheckbash.task;

import android.Manifest;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.telephony.TelephonyManager;
import android.text.Layout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wyh.intelcheckbash.HttpUtil;
import com.example.wyh.intelcheckbash.LocalStorage;
import com.example.wyh.intelcheckbash.LoginActivity;
import com.example.wyh.intelcheckbash.MainActivity;
import com.example.wyh.intelcheckbash.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Array;
import java.text.DecimalFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;

import com.example.wyh.intelcheckbash.SeismicActivity;
import com.example.wyh.intelcheckbash.bluetoothchat.BluetoothChatFragment;
import com.example.wyh.intelcheckbash.common.SysExitUtil;
import com.example.wyh.intelcheckbash.sqlite.TaskDbHelper;
import com.example.wyh.intelcheckbash.temptemperature.ThermometricActivity;
import com.google.zxing.activity.CaptureActivity;
//import com.umeng.commonsdk.UMConfigure;

import static android.view.View.inflate;


/**
 * Created by chen on 17/10/19.
 */


public class TaskCheckActivity extends AppCompatActivity {

    public static String LOCALSTATUS = "localStatus";
    public static String LOCALCHECKPOSITION = "localCheckPosition";
    public static String COLOORGREEN = "#00c61c";
    public static String COLORYELLOW = "#ebff00";

    private JSONObject mAllTaskData = new JSONObject();
    private JSONObject mCurrentTaskData;
    private JSONObject mCurrentAreaData;
    private JSONObject mCurrentEquipment;
    private JSONObject mCurrentCompleteEquipmentInfo;

    private JSONArray mAreaAllCompleteEquipment;

    private ArrayList<String> mTaskNames = new ArrayList<String>();
    private ArrayList<String> mTaskAreaNames = new ArrayList<String>();
    private ArrayList<String> mTaskEquipments = new ArrayList<String>();
    private ArrayList<String> mTaskStatus = new ArrayList<String>();
    private Spinner mTaskNamesSpinner;
    private Spinner mTaskAreaNamesSpinner;
    private Spinner mTaskEquipmentNameSpinner;
    private Spinner mTaskStatusSpinner;
    private String mItemStatus;

    private ListView mCheckInfoListView;
    private ListViewAdapter adapter;
    private ArrayList<ListViewItem> mViewItemsArraylists;
    BluetoothChatFragment mFragment = MainActivity.getInstance();

    private Button mSaveTaskBtn;

    private String mScanBarcodeTime;
    private String mScanBarcodeResult;

    private String mTestValue = "";
    public String mDeviceToken = "";
    public String mYhxtm = "";
    public String mUserName = "";

    public JSONObject mAllScanInfos;

    public TextView mCheckedTimeShow;

    public boolean setting_status = false;
    public boolean isCHeckQXYCComplete = false;

    public ProgressBar upload_task_progress_id;
    public LinearLayout upload_layout;
    public TextView upload_title;

    public boolean is_jump_to_next = false;

    public void initActionBar() {

        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("");
            actionBar.setDisplayShowHomeEnabled(false);
            actionBar.setDisplayShowCustomEnabled(true);
            LayoutInflater inflator = (LayoutInflater) this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = inflator.inflate(R.layout.check_task_actionbar, new LinearLayout(TaskCheckActivity.this), false);
            ActionBar.LayoutParams layout = new ActionBar.LayoutParams(
                    android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT, android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT);
            actionBar.setCustomView(v, layout);
            Toolbar parent = (Toolbar) v.getParent();
            parent.setContentInsetsAbsolute(0, 0);
        }
        TextView actionBarTitle = (TextView) findViewById(R.id.action_bar_title);
        actionBarTitle.setText("巡检任务");

        RelativeLayout bar_back_btn = (RelativeLayout) findViewById(R.id.bar_check_back_btn);
        bar_back_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mAllTaskData = null;
                mCurrentTaskData = null;
                mCurrentAreaData = null;
                mAreaAllCompleteEquipment = null;
                mCurrentEquipment = null;
                mCurrentCompleteEquipmentInfo = null;
                TaskCheckActivity.this.finish();
            }
        });
        RelativeLayout scanBarcodeBtn = (RelativeLayout) findViewById(R.id.scan_barcode_id);
        scanBarcodeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                scanBarcodeOrigion();
            }
        });
        Button completeTaskBtn = (Button) findViewById(R.id.complete_task_btn);
        completeTaskBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setting_status = true;
                try {
                    String rwxtm = mCurrentTaskData.getString("xtm");
                    HttpUtil.requestNetForCompleteTask(mYhxtm, rwxtm, mDeviceToken, getTimeString(new Date()), TaskCheckActivity.this);
                } catch (Exception e) {
                }

            }
        });
    }

    public void updateCompletedTask(String rwxtm) {
        TaskDbHelper taskDbHelper = new TaskDbHelper(TaskCheckActivity.this);
        SQLiteDatabase db = taskDbHelper.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("task_id", rwxtm);
        cv.put("is_complete", true);
        int success = db.update("task", cv, "task_id=? and user_id=? and time=?", new String[]{String.valueOf(rwxtm),
                String.valueOf(LocalStorage.getUserXtm(TaskCheckActivity.this)), String.valueOf(HttpUtil.getCurrentDateString())});
        Log.e("success", success + "");
        db.close();

        try {
            JSONArray allTasks = mAllTaskData.getJSONArray("data");
            mCurrentTaskData.put("is_complete", "1");
            allTasks.put(mTaskNamesSpinner.getSelectedItemPosition(), mCurrentTaskData);
            mAllTaskData.put("data", allTasks);
        } catch (JSONException e) {

        }
        updateCompleteBtnStatus();
    }

    public void scanBarcodeOrigion() {
        setting_status = true;
        if (ContextCompat.checkSelfPermission(TaskCheckActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(TaskCheckActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
        } else {
            startActivityForResult(new Intent(TaskCheckActivity.this, CaptureActivity.class), 1000);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_CAMERA) {
            scanBarcodeOrigion();
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            mAllTaskData = null;
            mCurrentTaskData = null;
            mCurrentAreaData = null;
            mAreaAllCompleteEquipment = null;
            mCurrentEquipment = null;
            mCurrentCompleteEquipmentInfo = null;
            this.finish();
        }
        return true;
//        return super.onKeyDown(keyCode, event);
    }

    public void updateCompleteBtnStatus() {

        try {
//            Log.e("is_complete", mCurrentTaskData.getString("is_complete"));
            if (mCurrentTaskData.getString("is_complete").equals("1")) {
                String strCompleted = "已完成";
                Button completeTaskBtn = (Button) findViewById(R.id.complete_task_btn);
                completeTaskBtn.setText(strCompleted);
                completeTaskBtn.setEnabled(false);
            } else {
                String strCompleted = "未完成";
                Button completeTaskBtn = (Button) findViewById(R.id.complete_task_btn);
                completeTaskBtn.setText(strCompleted);
                completeTaskBtn.setEnabled(true);
            }
        } catch (Exception e) {

        }

    }

    public int getPositionOfSpinner(String name,ArrayList<String> nameList)
    {
        int index = 0;
        for (int i = 0; i < nameList.size(); i ++)
        {
            if (name.equals(nameList.get(i)))
            {
                index = i;
            }
        }
        return index;
    }
    public int getPositionOfEquipmentSpinner(String name,ArrayList<String> nameList)
    {
        int index = 0;
        for (int i = 0; i < nameList.size(); i ++)
        {
            String equipmentName = nameList.get(i);
            equipmentName = equipmentName.substring(0,equipmentName.length() - 5);
            if (name.equals(equipmentName))
            {
                index = i;
            }
        }
        return index;
    }

    public void initHideLinearLayout()
    {
        upload_layout = (LinearLayout)findViewById(R.id.upload_layout_id);
        upload_layout.setVisibility(View.INVISIBLE);
        upload_task_progress_id = (ProgressBar)findViewById(R.id.upload_task_progress_id);
        upload_title = (TextView)findViewById(R.id.upload_title);
        upload_task_progress_id.setVisibility(View.INVISIBLE);
        upload_title.setVisibility(View.INVISIBLE);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_check);
        SysExitUtil.activityList.add(TaskCheckActivity.this);

        initHideLinearLayout();

        mAllScanInfos = LocalStorage.getObject(TaskCheckActivity.this, "allScanInfo");
        getHttpHeads();
        initActionBar();
        int taskIndex = 0;
        int areaIndex = 0;
        int equipmentIndex = 0;
        JSONObject localCheckPosition = LocalStorage.getObject(TaskCheckActivity.this,LOCALCHECKPOSITION);
        Log.e("create------localCheckPosition",localCheckPosition.toString());
        try {
            mAllTaskData = getAllTaskList();
            mTaskNames = getTaskInfo(mAllTaskData);
            Log.e("mAllTaskData========",mAllTaskData.toString());
            try {
                if (localCheckPosition.getString("date").equals(HttpUtil.getCurrentDateString()))
                {
                    String taskName = localCheckPosition.getString("rwdescription");
                    taskIndex = getPositionOfSpinner(taskName,mTaskNames);
                }
            }catch (JSONException e)
            {

            }
            mTaskAreaNames = getTaskInfo(mAllTaskData.getJSONArray("data").getJSONObject(taskIndex));
            try {
                if (localCheckPosition.getString("date").equals(HttpUtil.getCurrentDateString()))
                {
                    String areaName = localCheckPosition.getString("qydescription");
                    areaIndex = getPositionOfSpinner(areaName,mTaskAreaNames);
                }
            }catch (JSONException e)
            {

            }
            mTaskEquipments = getAllEquipmentNames(mAllTaskData.getJSONArray("data").getJSONObject(taskIndex).getJSONArray("data").getJSONObject(areaIndex));
            try {
                if (localCheckPosition.getString("date").equals(HttpUtil.getCurrentDateString()))
                {
                    String equipmentName = localCheckPosition.getString("sbdescription");
                    equipmentIndex = getPositionOfEquipmentSpinner(equipmentName,mTaskEquipments);
                    Log.e("equipmentName",equipmentName + ":" + equipmentIndex);
                    Log.e("mTaskEquipments",mTaskEquipments.toString());
                }
            }catch (JSONException e)
            {

            }
            mTaskStatus = getTaskStatus();
            mCurrentTaskData = mAllTaskData.getJSONArray("data").getJSONObject(taskIndex);
            mCurrentAreaData = mCurrentTaskData.getJSONArray("data").getJSONObject(areaIndex);
            mAreaAllCompleteEquipment = getAreaAllCompleteEquipment(mCurrentAreaData);

            saveTempCheckTaskInLocal();
            mCurrentEquipment = mCurrentAreaData.getJSONArray("data").getJSONObject(equipmentIndex);
            updateCompleteBtnStatus();
            if (mAllScanInfos.length() == 0) {
                initAllScanInfos();
            }else
            {
                String xtm = mAllTaskData.getJSONArray("data").getJSONObject(0).getString("xtm");
                try {
                    if (mAllScanInfos.getString(xtm).length() != 0)
                    {
                    }
                }catch (JSONException e)
                {
                    initAllScanInfos();
                }
            }
        } catch (JSONException e) {
            Log.e("JSONException＝＝＝＝＝＝＝＝ e",e.getMessage());
        }

        Log.e("index",taskIndex + ":" +areaIndex+":"+equipmentIndex);
        mCheckedTimeShow = (TextView) findViewById(R.id.check_time_show);
        mTaskNamesSpinner = initTaskNameSpinner("选择巡检任务", R.id.select_task,taskIndex);
        mTaskNamesSpinner.setSelection(taskIndex);
        mTaskAreaNamesSpinner = initTaskAreaSpinner();
        mTaskAreaNamesSpinner.setSelection(areaIndex);

        mTaskEquipmentNameSpinner = initTaskEquipmentSpinner();
        mTaskEquipmentNameSpinner.setSelection(equipmentIndex);
        //todo 设置完
//        setting_status = true;

        mTaskStatusSpinner = initTaskStatusSpinner();
        initTaskChangeButton();
        initRegionChangeButton();
        initEquipmentChangeButton();
        initStatusChangeButton();
        initPreEquipmentBtn();
        initNextEquipmentBtn();


        mCheckInfoListView = (ListView) findViewById(R.id.show_check_info_lsit_view);

        if (mAllTaskData instanceof JSONObject) {
            if (mTaskNames.size() != 0 && mAreaAllCompleteEquipment != null) {
                statusSpinnerIndex0(equipmentIndex);
            } else {
                Toast.makeText(TaskCheckActivity.this, "下载的巡检任务为空，请核实！", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(TaskCheckActivity.this, "请下载今天的巡检任务！", Toast.LENGTH_SHORT).show();
        }
        mSaveTaskBtn = (Button) findViewById(R.id.save_task_btn_id);
        mSaveTaskBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setting_status = true;
                // TODO: 18/1/5 获取本地存储的扫描区域和扫描时间
                try {
                    JSONArray scanJSONArray = mAllScanInfos.getJSONArray(mCurrentTaskData.getString("xtm"));
                    for (int i = 0; i < scanJSONArray.length(); i++) {
                        if (scanJSONArray.getJSONObject(i).getString("scanResult").equals(mTaskAreaNamesSpinner.getSelectedItem().toString())) {
                            mScanBarcodeResult = scanJSONArray.getJSONObject(i).getString("scanResult");
                            mScanBarcodeTime = scanJSONArray.getJSONObject(i).getString("scanTime");
                            break;

                        }
                    }
                }catch (JSONException e)
                {

                }
                //检测获取的填写数据
                Log.e("+========mAreaAllCompleteEquipment",""+mAreaAllCompleteEquipment.length());
                for (int m = 0; m < mAreaAllCompleteEquipment.length(); m ++)
                {
                    try {
                        JSONObject completeEquipment = mAreaAllCompleteEquipment.getJSONObject(m);
                        completeEquipment.put("smqyms", mScanBarcodeResult);
                        completeEquipment.put("smsj", mScanBarcodeTime);
//                        completeEquipment.put("date", getTimeString(new Date()));
                        JSONArray xmdata = completeEquipment.getJSONArray("xmdata");
                        for (int i = 0; i < xmdata.length(); i++) {
                            JSONObject xmInfo;
                            try {
                                xmInfo = xmdata.getJSONObject(i);
                            }catch (JSONException e)
                            {
                                continue;
                            }
                            xmInfo.put("pk", java.util.UUID.randomUUID().toString());
                            try {
                                if (!xmInfo.getString("sfycd").equals("1")) {
                                    xmdata.put(i, getNewXMInfo(xmInfo));
                                }
                            } catch (JSONException e) {
                                xmdata.put(i, getNewXMInfo(xmInfo));
                            }
                        }
                        Log.e("======completeEquipment==", completeEquipment.toString());
                    }catch (JSONException e)
                    {

                    }
                }
//                Log.e("============",mAreaAllCompleteEquipment.toString());
                if (mAreaAllCompleteEquipment.length() > 0 &&
                        judgeIsScanBarcodeInfo(mAreaAllCompleteEquipment) &&
                        judgeAllXMInfoIsComplete(mAreaAllCompleteEquipment))
                {
                    uploadOneEquipmentInfo();
                }

            }
        });
    }
    public void showUploadHideView()
    {
        upload_layout.setVisibility(View.VISIBLE);
        upload_title.setVisibility(View.VISIBLE);
        upload_title.setText("正在上传：0%");
        upload_task_progress_id.setVisibility(View.VISIBLE);
        upload_task_progress_id.setMax(mAreaAllCompleteEquipment.length());
    }
    public void uploadOneEquipmentInfo()
    {
        try {
            Date currentDate = new Date();
            if (!mCheckedTimeShow.getText().toString().equals("") &&
                    currentDate.getTime() - HttpUtil.StrToDate(mCheckedTimeShow.getText().toString()).getTime() < 2 * 60 * 1000) {
                showAlert();
            } else {
                showUploadHideView();
                saveCheckTaskInLocal();
//                Log.e("============",uploadCompleteEquipment.toString());
                JSONObject uploadCompleteEquipment = mAreaAllCompleteEquipment.getJSONObject(0);
                HttpUtil.requestNetForPostUploadData(mYhxtm, mDeviceToken, uploadCompleteEquipment, TaskCheckActivity.this);
            }
        }catch (JSONException e)
        {

        }

    }
    public boolean judgeIsScanBarcode()
    {
        boolean isScaned = true;
        String areaName = mTaskAreaNamesSpinner.getSelectedItem().toString();
        if (mScanBarcodeResult == null || !mScanBarcodeResult.equals(areaName))
        {
            isScaned = false;
        }
        return isScaned;
    }
    public boolean judgeIsBugUncomplete(JSONObject info)
    {
        boolean isComplete = true;
        try {
            if (info.getString("isqx").equals("1") &&
                    (info.getString("qxms").length() == 0 || info.getString("qxdj").length() == 0
                    || info.getString("lxzy").length() == 0 || info.getString("lxr").length() == 0))
            {
                isComplete = false;
            }
            if (info.getString("sfycd").equals("1") && info.getString("qxms").length() == 0)
            {
                isComplete = false;
            }
        }catch (JSONException e)
        {
            isComplete = false;
        }
        return isComplete;
    }
    public boolean judgeIsScanBarcodeInfo(JSONArray allCompleteEquipment)
    {
        boolean isScanBarcode = true;
        if (!judgeIsScanBarcode())
        {
            // TODO: 17/12/28 弹框展示是否扫描二维码，如果扫描，打开扫描二维码
            showScanBarcodeAlert(allCompleteEquipment);
            isScanBarcode = false;
        }
        return isScanBarcode;
    }

    public void showFillUnCompleteQXYCAlert(final int equipmentIndex, final int xmIndex)
    {
        LayoutInflater layoutInflater = LayoutInflater.from(TaskCheckActivity.this);
        final View layout = layoutInflater.inflate(R.layout.alert_dialog,
                null);
        final AlertDialog alertDialog = new AlertDialog.Builder(TaskCheckActivity.this).setTitle("").setView(layout)
                .setPositiveButton("", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .setNegativeButton("", null).show();

        TextView alert_title = (TextView) layout.findViewById(R.id.alert_title);
        alert_title.setText("您所在区域有缺陷或异常项目未填写，是否立即核实？");
        Button confirm = (Button) layout.findViewById(R.id.alert_confirm);
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
                // TODO: 17/12/28 跳转到未填写完整的信息页面
                mTaskEquipmentNameSpinner.setSelection(equipmentIndex);
                // TODO: 17/12/29 跳转到项目缺陷或者异常未填写完整的页面
                isCHeckQXYCComplete = true;
                Handler mainHandler = new Handler(Looper.getMainLooper());
                mainHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        jumpToCheckInfoActivity(xmIndex);
                    }
                },1000);

            }
        });
        Button cancle = (Button) layout.findViewById(R.id.alert_cancle);
        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
    }
    public void showFillUnCompleteAlert(final int equipmentIndex, int xmIndex) {
        LayoutInflater layoutInflater = LayoutInflater.from(TaskCheckActivity.this);
        final View layout = layoutInflater.inflate(R.layout.alert_dialog,
                null);
        final AlertDialog alertDialog = new AlertDialog.Builder(TaskCheckActivity.this).setTitle("").setView(layout)
                .setPositiveButton("", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .setNegativeButton("", null).show();

        TextView alert_title = (TextView) layout.findViewById(R.id.alert_title);
        alert_title.setText("您所在区域有项目检查结果未填写完整，是否立即核实？");
        Button confirm = (Button) layout.findViewById(R.id.alert_confirm);
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
                // TODO: 17/12/28 跳转到未填写完整的信息页面
                mTaskEquipmentNameSpinner.setSelection(equipmentIndex);

            }
        });
        Button cancle = (Button) layout.findViewById(R.id.alert_cancle);
        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
    }
    public void showScanBarcodeAlert(final JSONArray allCompleteEquipment) {
        LayoutInflater layoutInflater = LayoutInflater.from(TaskCheckActivity.this);
        final View layout = layoutInflater.inflate(R.layout.alert_dialog,
                null);
        final AlertDialog alertDialog = new AlertDialog.Builder(TaskCheckActivity.this).setTitle("").setView(layout)
                .setPositiveButton("", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .setNegativeButton("", null).show();

        TextView alert_title = (TextView) layout.findViewById(R.id.alert_title);
        alert_title.setText("您未扫描区域二维码，是否立即扫描？");
        Button confirm = (Button) layout.findViewById(R.id.alert_confirm);
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
                scanBarcodeOrigion();
            }
        });
        Button cancle = (Button) layout.findViewById(R.id.alert_cancle);
        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
                // TODO: 17/12/28 继续巡检
                if (judgeAllXMInfoIsComplete(allCompleteEquipment))
                {
                    uploadOneEquipmentInfo();
                }
            }
        });
    }

    public boolean judgeAllXMInfoIsComplete(JSONArray allCompleteEquipment)
    {
        boolean isCdjgComplete = true;
        int unCompleteIndex = -1;
        int unCompleteXMIndex = -1;
        boolean isQXComplete = true;
        for (int i = 0; i < allCompleteEquipment.length(); i ++)
        {
            try {
                JSONObject completeEquipment = allCompleteEquipment.getJSONObject(i);
                JSONArray xmInfos = completeEquipment.getJSONArray("xmdata");
                for (int m = 0; m < xmInfos.length(); m ++)
                {
                    JSONObject info = xmInfos.getJSONObject(m);
                    if (info.getString("cdjg").length() == 0)
                    {
                        isCdjgComplete = false;
                        unCompleteIndex = i;
                        unCompleteXMIndex = m;
                        break;

                    }
                    else if (!judgeIsBugUncomplete(info))
                    {
                        unCompleteIndex = i;
                        unCompleteXMIndex = m;
                        isQXComplete = false;
                        break;
                    }
                }
                if (isQXComplete == false || isCdjgComplete == false)
                {
                    break;
                }
            }catch (JSONException e)
            {

            }
        }

        if (isCdjgComplete == false)
        {
            showFillUnCompleteAlert(unCompleteIndex,unCompleteXMIndex);
        }
        else if (isQXComplete == false)
        {
            showFillUnCompleteQXYCAlert(unCompleteIndex,unCompleteXMIndex);
        }

        return isCdjgComplete && isQXComplete;
    }


    public JSONObject initAEquipmentcompleteXMInfo(JSONObject currentAreaData,JSONObject equipment, String taskId, String areaId, String equipmentId, String status) {
        JSONObject completeXmInfo = new JSONObject();
        TaskDbHelper taskDbHelper = new TaskDbHelper(TaskCheckActivity.this);
        SQLiteDatabase db = taskDbHelper.getReadableDatabase();
//        String query = "time = '" + HttpUtil.getCurrentDateString() +
//                "' and user_id = '" + LocalStorage.getUserXtm(TaskCheckActivity.this)
//                + "'" + " and task_id = '" + taskId + "'" + " and area_id = '" + areaId + "'" + " and equipment_id = '" + equipmentId + "'"
//                + " and equipmentStatus = '" + status + "'";
        String query = "user_id = '" + LocalStorage.getUserXtm(TaskCheckActivity.this)
                + "'" + " and task_id = '" + taskId + "'" + " and area_id = '" + areaId + "'" + " and equipment_id = '" + equipmentId + "'"
                + " and equipmentStatus = '" + status + "'";
        String[] columns = {"data"};
        Cursor cursor = null;
        try {
            cursor = db.query("complete_task", columns, query, null, null, null, null);
            if (cursor.getCount() == 0) {
                completeXmInfo = initRecodeEquipmentWithAreaInfo(currentAreaData,equipment,status);
            }
            while (cursor.moveToNext()) {
                if (cursor.getColumnIndex("data") > -1) {
                    String data = cursor.getString(cursor.getColumnIndex("data"));
//                    Log.e("data==========",data);
                    try {
                        completeXmInfo = new JSONObject(data);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

            }

        } catch (SQLException e) {
        }
        //关闭数据库
        db.close();
        return completeXmInfo;
    }

    public JSONObject initRecodeEquipmentWithAreaInfo(JSONObject currentAreaData,JSONObject equipment,String itemStatus)
    {
        JSONObject uploadEquipmentData = new JSONObject();
        try {
            uploadEquipmentData.put("xjr", mUserName);
            uploadEquipmentData.put("sbms", equipment.getString("description"));
            uploadEquipmentData.put("qysbxtm", equipment.getString("xtm")); //shebi id
            uploadEquipmentData.put("sbzt", itemStatus);
            uploadEquipmentData.put("rwms", mCurrentTaskData.getString("description"));
            uploadEquipmentData.put("rwxtm", mCurrentTaskData.getString("xtm")); //renwu id
            uploadEquipmentData.put("qyms", currentAreaData.getString("description"));
            uploadEquipmentData.put("xdjqyxtm", currentAreaData.getString("xtm")); //quyu id
            uploadEquipmentData.put("smqyms", mScanBarcodeResult);
            uploadEquipmentData.put("smsj", mScanBarcodeTime);
            JSONArray xmInfo = new JSONArray();
            JSONArray xmInfoBZ = equipment.getJSONArray("data");
            for (int i = 0; i < xmInfoBZ.length(); i++) {
                if (xmInfoBZ.getJSONObject(i).getString("qtd").contains(itemStatus)){
                    String cdjg = "";
                    String sfycd = "0";
                    if (xmInfoBZ.getJSONObject(i).getString("cdlx").equals("GC")
                            && xmInfoBZ.getJSONObject(i).getString("jgzmr").equals("1")) {
                        JSONArray cdjgzlb = xmInfoBZ.getJSONObject(i).getJSONArray("cdjgzlb");
                        cdjg = cdjgzlb.getJSONObject(0).getString("sfmrx").equals("1") ? cdjgzlb.getJSONObject(0).getString("z") : cdjgzlb.getJSONObject(1).getString("z");
                        sfycd = cdjgzlb.getJSONObject(0).getString("sfmrx").equals("1") ? cdjgzlb.getJSONObject(0).getString("sfyc") : cdjgzlb.getJSONObject(1).getString("sfyc");
                    }
                    JSONObject info = new JSONObject();
                    info.put("cdjg", cdjg);
                    info.put("equipment_code", equipment.getString("equipment_code"));
                    info.put("isqx", "0");
                    info.put("sbxt", currentAreaData.getString("description"));
                    info.put("sfgld", "");
                    info.put("sfycd", sfycd);
                    info.put("xmms", xmInfoBZ.getJSONObject(i).getString("description"));
                    info.put("xmxtm", xmInfoBZ.getJSONObject(i).getString("xtm"));
                    xmInfo.put(info);
                }
            }
            uploadEquipmentData.put("xmdata", xmInfo);
        } catch (JSONException e) {
            Log.e("JSONException e", e.toString());
        }
        return uploadEquipmentData;
    }

    public JSONArray getAreaAllCompleteEquipment(JSONObject currentAreaData)
    {
        JSONArray areaAllCompleteEquipments = new JSONArray();
        try {
            JSONArray allEquipments = currentAreaData.getJSONArray("data");
            for (int m = 0; m < allEquipments.length(); m ++)
            {
                JSONObject equipment = allEquipments.getJSONObject(m);

                JSONObject localStatus = LocalStorage.getObject(TaskCheckActivity.this, LOCALSTATUS + HttpUtil.getCurrentDateString());
                String itemStatus = equipment.getString("sbzt").length() == 0 ? "运行" : equipment.getString("sbzt");
                String taskId = "";
                String areaId = "";
                String equipmentId = "";
                try {
                    taskId = mCurrentTaskData.getString("xtm");
                    areaId = mCurrentAreaData.getString("xtm");
                    equipmentId = equipment.getString("xtm");
                    itemStatus = localStatus.getString(equipment.getString("xtm"));
                }catch (JSONException e)
                {
                }
                JSONObject uploadEquipmentData = initAEquipmentcompleteXMInfo(currentAreaData, equipment,taskId, areaId, equipmentId, itemStatus);
                areaAllCompleteEquipments.put(uploadEquipmentData);
            }
        }catch (JSONException e)
        {

        }
//        Log.e("areaAllCompleteEquipments.length",areaAllCompleteEquipments.toString());
        return areaAllCompleteEquipments;
    }

    public void initAllScanInfos()
    {
        try {
            mAllScanInfos = new JSONObject();
            for (int i = 0; i < mAllTaskData.getJSONArray("data").length(); i++) {
                mAllScanInfos.put(mAllTaskData.getJSONArray("data").getJSONObject(i).getString("xtm"), new JSONArray());
            }
        }catch (JSONException e)
        {

        }
    }
    public void showAlert() {
        LayoutInflater layoutInflater = LayoutInflater.from(TaskCheckActivity.this);
        final View layout = layoutInflater.inflate(R.layout.alert_dialog,
                null);
        final AlertDialog alertDialog = new AlertDialog.Builder(TaskCheckActivity.this).setTitle("").setView(layout)
                .setPositiveButton("", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .setNegativeButton("", null).show();

        TextView alert_title = (TextView) layout.findViewById(R.id.alert_title);
        alert_title.setText("确定要保存并上传巡检任务吗？");
        Button confirm = (Button) layout.findViewById(R.id.alert_confirm);
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
                showUploadHideView();
                saveCheckTaskInLocal();
                try {
                    JSONObject uploadCompleteEquipment = mAreaAllCompleteEquipment.getJSONObject(0);
                    HttpUtil.requestNetForPostUploadData(mYhxtm, mDeviceToken, uploadCompleteEquipment, TaskCheckActivity.this);
                }catch (JSONException e)
                {
                }
            }
        });
        Button cancle = (Button) layout.findViewById(R.id.alert_cancle);
        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
    }

    public void jumpToCheckInfoActivity(int position) {
        Intent intent = new Intent(TaskCheckActivity.this, CheckInfoActivity.class);
        try {
            JSONArray currentStatusEquipments = new JSONArray();
            for (int i = 0; i < mCurrentEquipment.getJSONArray("data").length(); i ++)
            {
                if (mCurrentEquipment.getJSONArray("data").getJSONObject(i).getString("qtd").contains(mItemStatus))
                {
                    currentStatusEquipments.put(mCurrentEquipment.getJSONArray("data").getJSONObject(i));
                }
            }
            intent.putExtra("checkDetail", currentStatusEquipments.getJSONObject(position).toString());
            intent.putExtra("xmInfo", getXMInfo(position).toString());
            intent.putExtra("checkOrigin", mTaskAreaNamesSpinner.getSelectedItem().toString());
//            intent.putExtra("equipment_code", mCurrentEquipment.getString("equipment_code"));
        } catch (Exception e) {
        }
        startActivityForResult(intent, position);
    }

    public void saveTempCheckTaskInLocal()
    {
        JSONObject localStatus = LocalStorage.getObject(TaskCheckActivity.this, LOCALSTATUS + HttpUtil.getCurrentDateString());
        // TODO: 17/12/27 给每一个设备添加默认状态
        for (int i = 0; i < mAreaAllCompleteEquipment.length(); i ++)
        {
            try {
                JSONObject equipment = mAreaAllCompleteEquipment.getJSONObject(i);
//                Log.e("上传状态",equipment.getString("isUploadSuccess") + ":" + equipment.getString("qysbxtm"));
                localStatus.put(equipment.getString("qysbxtm"), equipment.getString("sbzt"));
            }catch (JSONException e)
            {

            }
        }
        // TODO: 17/12/27 添加上传状态并保存数据到数据库
        LocalStorage.saveObject(TaskCheckActivity.this, LOCALSTATUS + HttpUtil.getCurrentDateString(), localStatus);
//        Log.e("===========","=======================");
        for (int i = 0; i < mAreaAllCompleteEquipment.length(); i ++)
        {
            try {
                JSONObject equipment = mAreaAllCompleteEquipment.getJSONObject(i);
                JSONArray types = getAllTypes(mCurrentAreaData.getJSONArray("data").getJSONObject(i),equipment.getString("sbzt"));
                saveTempCompleteXmInfo(equipment,types);
//                Log.e("上传状态",equipment.getString("isUploadSuccess") + ":" + equipment.getString("qysbxtm"));
            }catch (JSONException e)
            {

            }
        }
    }

    public void saveCheckTaskInLocal() {
        for (int m = 0; m < mAreaAllCompleteEquipment.length(); m ++)
        {
            try {
                JSONObject completeEquipment = mAreaAllCompleteEquipment.getJSONObject(m);
                completeEquipment.put("date", getTimeString(new Date()));
            }catch (JSONException e)
            {

            }
        }
        JSONObject localStatus = LocalStorage.getObject(TaskCheckActivity.this, LOCALSTATUS + HttpUtil.getCurrentDateString());
        try {
            // TODO: 17/12/27 给每一个设备添加默认状态
            for (int i = 0; i < mAreaAllCompleteEquipment.length(); i ++)
            {
                try {
                    JSONObject equipment = mAreaAllCompleteEquipment.getJSONObject(i);
                    localStatus.put(equipment.getString("qysbxtm"), equipment.getString("sbzt"));
                }catch (JSONException e)
                {

                }
            }
            // TODO: 17/12/27 添加上传状态并保存数据到数据库
            LocalStorage.saveObject(TaskCheckActivity.this, LOCALSTATUS + HttpUtil.getCurrentDateString(), localStatus);
            for (int i = 0; i < mAreaAllCompleteEquipment.length(); i ++)
            {
                try {
                    JSONObject equipment = mAreaAllCompleteEquipment.getJSONObject(i);
                    equipment.put("isUploadSuccess", "0");
                    JSONArray types = getAllTypes(mCurrentAreaData.getJSONArray("data").getJSONObject(i),equipment.getString("sbzt"));
                    saveCompleteXmInfo(equipment,types);
                }catch (JSONException e)
                {

                }
            }

//            mCurrentCompleteEquipmentInfo.put("isUploadSuccess", "0");
//            JSONArray types = getAllTypes(mCurrentEquipment,mItemStatus);
//            saveCompleteXmInfo(mCurrentCompleteEquipmentInfo,types);
            mCheckedTimeShow.setText(mCurrentCompleteEquipmentInfo.getString("date"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        HttpUtil.showToast(TaskCheckActivity.this, "保存数据成功", 500);
    }

//    //自定义Toast弹框展示时间
//    public static void showToast(final Activity activity, final String word, final long time) {
//        activity.runOnUiThread(new Runnable() {
//            public void run() {
//                final Toast toast = Toast.makeText(activity, word, Toast.LENGTH_LONG);
//                toast.show();
//                Handler handler = new Handler();
//                handler.postDelayed(new Runnable() {
//                    public void run() {
//                        toast.cancel();
//                    }
//                }, time);
//            }
//        });
//    }

    public JSONArray getAllTypes(JSONObject euqipment,String status)
    {
        JSONArray types = new JSONArray();
        try {
            for (int i = 0; i < euqipment.getJSONArray("data").length(); i ++)
            {
                if (euqipment.getJSONArray("data").getJSONObject(i).getString("qtd").contains(status))
                {
                    JSONObject typeInfo = new JSONObject();
                    typeInfo.put("cdlx",euqipment.getJSONArray("data").getJSONObject(i).getString("cdlx"));
                    types.put(typeInfo);
                }

            }
        }catch (JSONException e)
        {

        }
        return types;
    }
    public int uploadCount = 0;
    public void afterUploadSaveInLocal(final boolean isUploadSuccess, final JSONObject completeEquipmentInfo) {
        final Handler mainHander = new Handler(Looper.getMainLooper());
        mainHander.post(new Runnable() {
            @Override
            public void run() {
                if (isUploadSuccess) {
                    try {
                        String status = completeEquipmentInfo.getString("sbzt");
                        completeEquipmentInfo.put("isUploadSuccess", "1");
                        JSONArray types = getAllTypes(mCurrentAreaData.getJSONArray("data").getJSONObject(uploadCount),status);
                        saveCompleteXmInfo(completeEquipmentInfo,types);
                    } catch (Exception e) {

                    }
                } else {
                }
                uploadCount ++;
                try {
                    if (mAreaAllCompleteEquipment.length() > 0)
                    {
                        // TODO: 17/12/27 更新进度条
                        upload_task_progress_id.setProgress(uploadCount);
                    }
                    if (uploadCount < mAreaAllCompleteEquipment.length())
                    {
                        try {
                            DecimalFormat df   = new DecimalFormat("######0.0");
                            upload_title.setText("正在上传："+df.format(100.00*uploadCount/mAreaAllCompleteEquipment.length()) + "%");
                            JSONObject uploadCompleteInfo = mAreaAllCompleteEquipment.getJSONObject(uploadCount);
//                            Log.e("============",uploadCompleteInfo.toString());
                            HttpUtil.requestNetForPostUploadData(mYhxtm, mDeviceToken, uploadCompleteInfo, TaskCheckActivity.this);
                        }catch (JSONException e)
                        {

                        }

                    }
                    else
                    {
                        // TODO: 17/12/27 上传完成
                    upload_title.setText("上传完成");
                        Handler mainHandler = new Handler(Looper.getMainLooper());
                        mainHander.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                upload_layout.setVisibility(View.INVISIBLE);
                                upload_task_progress_id.setVisibility(View.INVISIBLE);
                                upload_title.setVisibility(View.INVISIBLE);
                                upload_task_progress_id.setProgress(0);
                                uploadCount = 0;
//                            upload_title.setText("正在上传");
                            }
                        },1000);

                    }
                }catch (Exception e)
                {
                    Log.e("正在上传立马退出页面",e.getMessage());
                }


//                jumpToNextEquipment("已经巡检到当前区域的最后一个设备了");
            }
        });
    }

    public void jumpToNextEquipment(String message)
    {
        int position = mTaskEquipmentNameSpinner.getSelectedItemPosition();
        if (position < mTaskEquipments.size() - 1) {
            mTaskEquipmentNameSpinner.setSelection(position + 1);
            updateTaskAreaEquipment(position + 1);
        }
        else
        {
            showDialog(TaskCheckActivity.this, message);
        }
    }
    public void updateListView(int position) {
        getListViewData();
        try {
            mCurrentCompleteEquipmentInfo = mAreaAllCompleteEquipment.getJSONObject(position);
//            Log.e("mCurrentCompleteEquipmentInfo",mCurrentCompleteEquipmentInfo.toString());
//            mCurrentCompleteEquipmentInfo = getCompleteXMInfo(mCurrentEquipment.getString("xtm"), mCurrentAreaData.getString("xtm"), mCurrentTaskData.getString("xtm"),-1,"");
            mCheckedTimeShow.setText("");
            mCheckedTimeShow.setText(mCurrentCompleteEquipmentInfo.getString("date"));
        } catch (JSONException e) {

        }
        final Context context = TaskCheckActivity.this;
        Handler mainHandler = new Handler(Looper.getMainLooper());
        try {
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    adapter = new ListViewAdapter(context, mViewItemsArraylists, mCurrentCompleteEquipmentInfo);
                    mCheckInfoListView.setAdapter(adapter);
                }
            });
        }catch (Exception e)
        {

        }
        //将巡检记录序号存到本地
        try {
            JSONObject localCheckPosition = LocalStorage.getObject(TaskCheckActivity.this,LOCALCHECKPOSITION);
            localCheckPosition.put("date",HttpUtil.getCurrentDateString());
            localCheckPosition.put("rwxtm",mCurrentCompleteEquipmentInfo.getString("rwxtm"));
            localCheckPosition.put("rwdescription",mCurrentTaskData.getString("description"));
            localCheckPosition.put("xdjqyxtm",mCurrentCompleteEquipmentInfo.getString("xdjqyxtm"));
            localCheckPosition.put("qydescription",mCurrentAreaData.getString("description"));
            localCheckPosition.put("qysbxtm",mCurrentCompleteEquipmentInfo.getString("qysbxtm"));
            localCheckPosition.put("sbdescription",mCurrentEquipment.getString("description"));
            LocalStorage.saveObject(TaskCheckActivity.this,LOCALCHECKPOSITION,localCheckPosition);
        }catch (JSONException e)
        {

        }


    }

    public void getEquipmentItemStatus(int position) {
        try {
            if (mAreaAllCompleteEquipment == null)
                return;
            mItemStatus = mAreaAllCompleteEquipment.getJSONObject(position).getString("sbzt");
            switch (mItemStatus) {
                case "运行":
                    mTaskStatusSpinner.setSelection(0);
                    break;
                case "备用":
                    mTaskStatusSpinner.setSelection(1);
                    break;
                case "停止":
                    mTaskStatusSpinner.setSelection(2);
                    break;
                case "检修":
                    mTaskStatusSpinner.setSelection(3);
                    break;
                default:
                    break;
            }
        } catch (JSONException e) {
        }
    }

    public void getListViewData() {
        mViewItemsArraylists = new ArrayList<ListViewItem>();
        try {
            if (mCurrentEquipment == null)
                return;
            for (int i = 0; i < mCurrentEquipment.getJSONArray("data").length(); i++) {

                HashMap<String, JSONObject> map = new HashMap<String, JSONObject>();
                JSONObject object = mCurrentEquipment.getJSONArray("data").getJSONObject(i);

                if (object.getString("qtd").contains(mItemStatus)) {
                    int type = 0;
                    if (object.getString("cdlx").equals("GC"))
                    {
                        type = 0;
                    }
                    else if (object.getString("cdlx").equals("CW") || object.getString("cdlx").equals("CZ"))
                    {
                        type = 1;
                    }
                    else if (object.getString("cdlx").equals("CB"))
                    {
                        type = 2;
                    }
//                    int type = object.getString("cdlx").equals("GC") ? 0 : 1;
                    map.put(mViewItemsArraylists.size() + "", object);
                    mViewItemsArraylists.add(new ListViewItem(type, map));
                }
            }

        } catch (JSONException e) {

        }
    }

    public void showDialog(Context context, String message) {
        LayoutInflater layoutInflater = LayoutInflater.from(context);
        final View layout = layoutInflater.inflate(R.layout.promot_alert,
                null);

        final AlertDialog alertDialog = new AlertDialog.Builder(context).setTitle("").setView(layout)
                .setPositiveButton("", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .setNegativeButton("", null).show();

        TextView alert_title = (TextView) layout.findViewById(R.id.promot_alert_title);
        alert_title.setText(message);
        Button confirm = (Button) layout.findViewById(R.id.promot_confirm);
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
    }

    public void saveScanResultInLocal(String scanBarcodeResult,String scanBarcodeTime,String xtm) {
        try {
            JSONArray scanJSONArray = mAllScanInfos.getJSONArray(mCurrentTaskData.getString("xtm"));
            boolean isExist = false;
            for (int i = 0; i < scanJSONArray.length(); i++) {
                if (scanJSONArray.getJSONObject(i).getString("scanResult").equals(scanBarcodeResult))
                    isExist = true;
            }
            if (isExist == false) {
                JSONObject scanInfo = new JSONObject();
                scanInfo.put("scanResult",scanBarcodeResult);
                scanInfo.put("scanTime",scanBarcodeTime);
                scanJSONArray.put(scanInfo);
                mAllScanInfos.put(mCurrentTaskData.getString("xtm"), scanJSONArray);
                LocalStorage.saveObject(TaskCheckActivity.this, "allScanInfo", mAllScanInfos);
            }
        } catch (JSONException e) {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        final Intent resultData = data;
        //扫描二维码

        if (requestCode == 1000) {
            try {
                String scanBarcodeResult = data.getStringExtra(CaptureActivity.SCAN_QRCODE_RESULT);
                if (!mTaskAreaNames.contains(scanBarcodeResult)) {
                    showDialog(TaskCheckActivity.this, "您扫描的区域未在任务中");
                    return;
                }
                mScanBarcodeResult = scanBarcodeResult;
                //如果扫描的区域正好是当前区域，则不再刷新列表
                if (!mTaskAreaNamesSpinner.getSelectedItem().toString().equals(scanBarcodeResult))
                {
                    int selectIndex = mTaskAreaNamesSpinner.getSelectedItemPosition();
                    mScanBarcodeTime = getTimeString(new Date());
                    for (int i = 0; i < mTaskAreaNames.size(); i++) {
                        if (mTaskAreaNames.get(i).equals(mScanBarcodeResult)) {
                            selectIndex = i;
                            break;
                        }
                    }
                    mTaskAreaNamesSpinner.setSelection(selectIndex);
                }

                mCurrentCompleteEquipmentInfo.put("smqyms", mScanBarcodeResult);
                mCurrentCompleteEquipmentInfo.put("smsj", mScanBarcodeTime);
                saveScanResultInLocal(mScanBarcodeResult,mScanBarcodeTime,mCurrentCompleteEquipmentInfo.getString("xdjqyxtm"));
            } catch (Exception e) {
                Log.e("扫描二维码失败", e.toString());
            }
        } else if (resultCode == 1001) {
            try {
                String defectInfo = data.getStringExtra("defectInfo");
                updateDefactBug(requestCode, new JSONObject(defectInfo));
            } catch (JSONException e) {
                e.printStackTrace();
            }

        } else if (resultCode == 1002 || resultCode == 1003) {
            mTestValue = resultData.getStringExtra("testValue");
            View itemView = mCheckInfoListView.getChildAt(requestCode - mCheckInfoListView.getFirstVisiblePosition());
            EditText test_result = (EditText) itemView.findViewById(R.id.show_seismic_id);
            if(!mTestValue.equals("－－")){
                test_result.setText(mTestValue);
                updateCheckValue(test_result,requestCode, mTestValue);
            }

        }
    }

    public void bluetoothConnectSuccessJumpToTestThermom(final int position)
    {
        final Handler handler = new Handler(Looper.getMainLooper());
        final Runnable runnable = new Runnable(){
            @Override
            public void run() {
                startActivityForResult(new Intent(TaskCheckActivity.this, ThermometricActivity.class), position);
            }
        };
        handler.postDelayed(runnable,1000);
    }
    public void bluetoothConnectSuccessJumpToTestSeismic(final int position)
    {
        final Handler handler = new Handler(Looper.getMainLooper());
        final Runnable runnable = new Runnable(){
            @Override
            public void run() {
                startActivityForResult(new Intent(TaskCheckActivity.this, SeismicActivity.class), position);
            }
        };
        handler.postDelayed(runnable,1000);
    }

    public void jumpToTestThermom(int position) {
        if (mFragment.mIsConnectedBlueTooth == false) {

            try {
                String bluetoothAddress = LocalStorage.getString(TaskCheckActivity.this,"blueToothAddress");
                if (bluetoothAddress.length() != 0)
                {
                    mFragment.setContext(TaskCheckActivity.this);
                    mFragment.position = position;
                    mFragment.setTestType("TaskCheckActivityTestThermom");
                    mFragment.connectDeviceWithAddress(bluetoothAddress);
                    MainActivity.setIsConnectedInFail(false);
                }else
                {
                    HttpUtil.showToast(TaskCheckActivity.this,"请先在设置页面连接蓝牙设备",1000);
                }
            }catch (Exception e)
            {
                Log.e("TaskCheckActivity == bluetooth",e.getMessage());
            }

        } else {
            startActivityForResult(new Intent(TaskCheckActivity.this, ThermometricActivity.class), position);
        }
    }

    public void jumpToTestSeismic(int position) {
        if (mFragment.mIsConnectedBlueTooth == false) {
            try {
                String bluetoothAddress = LocalStorage.getString(TaskCheckActivity.this,"blueToothAddress");
                if (bluetoothAddress.length() != 0)
                {
                    mFragment.setContext(TaskCheckActivity.this);
                    mFragment.position = position;
                    mFragment.setTestType("TaskCheckActivityTestSeismic");
                    mFragment.connectDeviceWithAddress(bluetoothAddress);
                    MainActivity.setIsConnectedInFail(false);
                }else
                {
                    HttpUtil.showToast(TaskCheckActivity.this,"请先在设置页面连接蓝牙设备",1000);
                }
            }catch (Exception e)
            {
                Log.e("TaskCheckActivity == bluetooth",e.getMessage());
            }
        } else {
            startActivityForResult(new Intent(TaskCheckActivity.this, SeismicActivity.class), position);
        }
    }
    public void checkCBxmInfoToCompleteInfo(EditText editText,int position, String checkCBinfo)
    {
//        Log.e("===========--------------",checkCBinfo.toString());
        if (mViewItemsArraylists.size() > 0 && is_jump_to_next == false)
        {
//            Log.e("======mAreaAllCompleteEquipment====before",mAreaAllCompleteEquipment.toString());
            JSONObject xmInfo;
            try {
                xmInfo = mCurrentCompleteEquipmentInfo.getJSONArray("xmdata").getJSONObject(position);
            } catch (JSONException e) {
                xmInfo = initXMInfo(position);
                e.printStackTrace();
            }
            try {

                xmInfo.put("cdjg", checkCBinfo);
                double test_value = Double.parseDouble(checkCBinfo);
                JSONObject standard_xminfo = mViewItemsArraylists.get(position).map.get(position + "");
                if (!standard_xminfo.getString("cdlx").equals("CB")) {
                    return;
                }
                double sxz = Double.parseDouble(standard_xminfo.getString("sxz"));
                double xxz = Double.parseDouble(standard_xminfo.getString("xxz"));
                String sfycd = (test_value < xxz || test_value > sxz) ? "1" : "0";
                xmInfo.put("sfycd", sfycd);
                xmInfo.put("sxz", standard_xminfo.getString("sxz"));
                xmInfo.put("xxz", standard_xminfo.getString("xxz"));
                mCurrentCompleteEquipmentInfo.getJSONArray("xmdata").put(position, xmInfo);
                mAreaAllCompleteEquipment.put(mTaskEquipmentNameSpinner.getSelectedItemPosition(),mCurrentCompleteEquipmentInfo);
//                Log.e("======mAreaAllCompleteEquipment",mAreaAllCompleteEquipment.toString());
                saveTempCheckTaskInLocal();
                if (sfycd.equals("1"))
                {
                    editText.setTextColor(Color.parseColor("#ff0000"));
                }
                else
                {
                    editText.setTextColor(Color.parseColor("#000000"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    public void initPreEquipmentBtn() {
        Button preEquipmentBtn = (Button) findViewById(R.id.pre_equipment_id);
        preEquipmentBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setting_status = true;
                int position = mTaskEquipmentNameSpinner.getSelectedItemPosition();
                if (position > 0) {
                    mTaskEquipmentNameSpinner.setSelection(position - 1);
                    updateTaskAreaEquipment(position - 1);
                } else {
                    showDialog(TaskCheckActivity.this, "已经是第一个设备了");
                }
            }
        });
    }

    public void initNextEquipmentBtn() {
        Button nextEquipmentBtn = (Button) findViewById(R.id.next_equipment_id);
        nextEquipmentBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setting_status = true;
                jumpToNextEquipment("已经是最后一个设备了");
            }
        });
    }

    public void initStatusChangeButton() {
        Button mPreTaskStatus = (Button) findViewById(R.id.preBtnStatus);
        mPreTaskStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int position = mTaskStatusSpinner.getSelectedItemPosition();
                if (position > 0) {
                    mTaskStatusSpinner.setSelection(position - 1);
                } else {
                    Toast.makeText(TaskCheckActivity.this, "已经是第一个状态了", Toast.LENGTH_SHORT).show();
                }
            }
        });
        Button mNextTaskStatus = (Button) findViewById(R.id.nextBtnStatus);
        mNextTaskStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int position = mTaskStatusSpinner.getSelectedItemPosition();
                if (position < mTaskStatus.size() - 1) {
                    mTaskStatusSpinner.setSelection(position + 1);
                } else {
                    Toast.makeText(TaskCheckActivity.this, "已经是最后一个状态了", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public void initTaskChangeButton() {
        Button mPreTaskButton = (Button) findViewById(R.id.preBtnTask);
        mPreTaskButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setting_status = true;
                int position = mTaskNamesSpinner.getSelectedItemPosition();
                if (position > 0) {
                    mTaskNamesSpinner.setSelection(position - 1);
                    updateTask(position - 1);
                } else {
                    Toast.makeText(TaskCheckActivity.this, "已经是第一个任务了", Toast.LENGTH_SHORT).show();
                }

            }
        });

        Button mNextTaskButton = (Button) findViewById(R.id.nextBtnTask);
        mNextTaskButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setting_status = true;
                int position = mTaskNamesSpinner.getSelectedItemPosition();
                if (position < mTaskNames.size() - 1) {
                    mTaskNamesSpinner.setSelection(position + 1);
                    updateTask(position + 1);
                } else {
                    Toast.makeText(TaskCheckActivity.this, "已经是最后一个任务了", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public void initRegionChangeButton() {
        Button mPreRegionButton = (Button) findViewById(R.id.preBtnRegion);
        mPreRegionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setting_status = true;
                int position = mTaskAreaNamesSpinner.getSelectedItemPosition();
                if (position > 0) {
                    mTaskAreaNamesSpinner.setSelection(position - 1);
                    updateTaskArea(position - 1);
                } else {
                    Toast.makeText(TaskCheckActivity.this, "已经是第一个区域了", Toast.LENGTH_SHORT).show();
                }
            }
        });
        Button mNextRegionButton = (Button) findViewById(R.id.nextBtnRegion);
        mNextRegionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setting_status = true;
                int position = mTaskAreaNamesSpinner.getSelectedItemPosition();
                if (position < mTaskAreaNames.size() - 1) {
                    mTaskAreaNamesSpinner.setSelection(position + 1);
                    updateTaskArea(position + 1);
                } else {
                    Toast.makeText(TaskCheckActivity.this, "已经是最后一个区域了", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public void initEquipmentChangeButton() {
        Button mPreEquipmentButton = (Button) findViewById(R.id.preBtnDevice);
        mPreEquipmentButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setting_status = true;
                int position = mTaskEquipmentNameSpinner.getSelectedItemPosition();
                if (position > 0) {
                    mTaskEquipmentNameSpinner.setSelection(position - 1);
                    updateTaskAreaEquipment(position - 1);
                } else {
                    Toast.makeText(TaskCheckActivity.this, "已经是第一个设备了", Toast.LENGTH_SHORT).show();
                }
            }
        });
        Button mNextEquipmentButton = (Button) findViewById(R.id.nextBtnDevice);
        mNextEquipmentButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setting_status = true;
                jumpToNextEquipment("已经是最后一个设备了");
            }
        });
    }

    public ArrayList<String> getTaskStatus() {
        ArrayList<String> list = new ArrayList<String>();
        list.add("运行");
        list.add("备用");
        list.add("停止");
        list.add("检修");
        return list;
    }

    public ArrayList<String> getAllEquipmentNames(JSONObject temp)
    {
        ArrayList<String> names = new ArrayList<String>();
        JSONObject localStatus = LocalStorage.getObject(TaskCheckActivity.this, LOCALSTATUS + HttpUtil.getCurrentDateString());
        try {
            JSONArray area = temp.getJSONArray("data");
            for (int j = 0; j < area.length(); j++) {
                JSONObject equipment = area.getJSONObject(j);
                String itemStatus = equipment.getString("sbzt").length() == 0 ? "运行" : equipment.getString("sbzt");
                try {
                    itemStatus = localStatus.getString(equipment.getString("xtm"));
                }catch (JSONException e)
                {
                }
                names.add(equipment.getString("description") + " - " + itemStatus);
            }
            return names;

        } catch (Exception e) {

        }
        return names;
    }

    public ArrayList<String> getTaskInfo(JSONObject temp) {
        ArrayList<String> names = new ArrayList<String>();
        try {
            JSONArray area = temp.getJSONArray("data");
            for (int j = 0; j < area.length(); j++) {
                names.add(area.getJSONObject(j).getString("description"));
            }
            return names;

        } catch (Exception e) {

        }
        return names;
    }

    public String getTimeString(Date time) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(time);
    }

    public void updateTask(int position) {
        try {
            mCurrentTaskData = mAllTaskData.getJSONArray("data").getJSONObject(position);
            mCurrentAreaData = mCurrentTaskData.getJSONArray("data").getJSONObject(0);
            mAreaAllCompleteEquipment = getAreaAllCompleteEquipment(mCurrentAreaData);
            saveTempCheckTaskInLocal();
            mCurrentEquipment = mCurrentAreaData.getJSONArray("data").getJSONObject(0);
            statusSpinnerIndex0(0);

            mTaskAreaNames = getTaskInfo(mCurrentTaskData);
            mTaskEquipments = getAllEquipmentNames(mCurrentAreaData);

            mTaskAreaNamesSpinner = initTaskAreaSpinner();
            mTaskEquipmentNameSpinner = initTaskEquipmentSpinner();

            updateCompleteBtnStatus();
        } catch (Exception e) {

        }
    }

    public int getCurrentEquipmentDefaultStatus()
    {
        int index = 0;
        try {
            String sbzt = mCurrentEquipment.getString("sbzt");
            if (!sbzt.equals(""))
            {
                switch (sbzt)
                {
                    case "运行":
                        index = 0;
                        break;
                    case "备用":
                        index = 1;
                        break;
                    case "停止":
                        index = 2;
                        break;
                    case "检修":
                        index = 3;
                        break;
                    default:
                        break;
                }
            }
        }catch (JSONException e)
        {

        }
        return index;
    }

    public void statusSpinnerIndex0(int position) {
        getEquipmentItemStatus(position);
        updateListView(position);
    }

    public void updateTaskArea(int position) {
        try {
            mCurrentAreaData = mCurrentTaskData.getJSONArray("data").getJSONObject(position);
            mAreaAllCompleteEquipment = getAreaAllCompleteEquipment(mCurrentAreaData);
            saveTempCheckTaskInLocal();
            mCurrentEquipment = mCurrentAreaData.getJSONArray("data").getJSONObject(0);
            statusSpinnerIndex0(0);

            mTaskEquipments = getAllEquipmentNames(mCurrentAreaData);
            mTaskEquipmentNameSpinner = initTaskEquipmentSpinner();
        } catch (Exception e) {

        }
    }

    public void updateTaskAreaEquipment(int position) {
//        Log.e("position",position+"=========updateTaskAreaEquipment");
        is_jump_to_next = true;
        try {
            mCurrentEquipment = mCurrentAreaData.getJSONArray("data").getJSONObject(position);
            statusSpinnerIndex0(position);
        } catch (Exception e) {

        }
    }

    public Spinner initTaskNameSpinner(String title, int id,int taskIndex) {
        final Spinner spinner = (Spinner) findViewById(id);
        spinner.setPrompt(title);
        ArrayAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mTaskNames){
            @Override
            public View getDropDownView(int position, View convertView,
                                        ViewGroup parent) {
                setting_status = true;
                View view = inflate(getContext(), R.layout.spinner_item,
                        null);
                TextView label = (TextView) view
                        .findViewById(R.id.spinner_item_test);
                label.setText(mTaskNames.get(position));
                return view;
            }
        };
        spinner.setAdapter(adapter);
        spinner.setSelection(taskIndex);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (setting_status == true)
                {
                    spinner.setSelection(position);
                    updateTask(position);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        return spinner;
    }

    public Spinner initTaskAreaSpinner() {
        final Spinner spinner = (Spinner) findViewById(R.id.select_region);
        spinner.setPrompt("选择区域");
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, mTaskAreaNames) {
            @Override
            public View getDropDownView(int position, View convertView,
                                        ViewGroup parent) {
                setting_status = true;
                View view = inflate(getContext(), R.layout.spinner_item,
                        null);
                TextView label = (TextView) view
                        .findViewById(R.id.spinner_item_test);
                label.setText(mTaskAreaNames.get(position));
                try {
                    JSONArray scanInfos = mAllScanInfos.getJSONArray(mCurrentTaskData.getString("xtm"));
                    boolean isScaned = false;
                    for (int i = 0; i < scanInfos.length(); i++) {
                        if (scanInfos.getJSONObject(i).getString("scanResult").equals(mTaskAreaNames.get(position))) {
                            isScaned = true;
                        }
                    }
                    if (isScaned) {
                        label.setTextColor(Color.parseColor(COLOORGREEN));
                    }
                } catch (JSONException e) {
                }
                return view;
            }
        };
        adapter.setDropDownViewResource(R.layout.spinner_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (setting_status == true)
                {
                    spinner.setSelection(position);
                    updateTaskArea(position);
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        return spinner;
    }

    public Spinner initTaskEquipmentSpinner() {
        final Spinner spinner = (Spinner) findViewById(R.id.select_equipment);
        spinner.setPrompt("选择设备");
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, mTaskEquipments) {
            @Override
            public View getDropDownView(int position, View convertView,
                                        ViewGroup parent) {
//                this.notifyDataSetChanged();

                setting_status = true;
                View view = inflate(getContext(), R.layout.spinner_item,
                        null);
                TextView label = (TextView) view
                        .findViewById(R.id.spinner_item_test);
                label.setText(mTaskEquipments.get(position));

                String saveStatus = "";
                try {
                    JSONObject localStatus = LocalStorage.getObject(TaskCheckActivity.this, LOCALSTATUS + HttpUtil.getCurrentDateString());
                    saveStatus = localStatus.getString(mCurrentAreaData.getJSONArray("data").getJSONObject(position).getString("xtm"));
                }
                catch (JSONException e)
                {
                    saveStatus = null;
                }

                if (saveStatus != null)
                {
                    try {
                        JSONArray allEquipments = mCurrentAreaData.getJSONArray("data");
                        JSONObject equipment = allEquipments.getJSONObject(position);
                        JSONArray allCompleteInfo = new JSONArray();
                        JSONArray xms = equipment.getJSONArray("data");
                        for (int j = 0; j < xms.length(); j++) {
                            if (xms.getJSONObject(j).getString("qtd").contains(saveStatus)) {
                                allCompleteInfo.put(xms.getJSONObject(j));
                            }
                        }
                        JSONObject localEquip = getCompleteXMInLocal(equipment.getString("xtm"),
                                mCurrentAreaData.getString("xtm"), mCurrentTaskData.getString("xtm"),saveStatus);

                        if (localEquip != null && localEquip.getJSONArray("xmdata").length() == allCompleteInfo.length()) {
                            boolean isChecked = true;
                            for (int i = 0; i < localEquip.getJSONArray("xmdata").length(); i ++)
                            {
                                try {
                                    JSONObject xmInfo = localEquip.getJSONArray("xmdata").getJSONObject(i);
                                }catch (JSONException e)
                                {
                                    isChecked = false;
                                }
                            }

                            label.setTextColor(isChecked?Color.parseColor(COLOORGREEN):Color.parseColor(COLORYELLOW));
                        }
                        if (localEquip != null && localEquip.getJSONArray("xmdata").length() < allCompleteInfo.length()) {
                            label.setTextColor(Color.parseColor(COLORYELLOW));
                        }

                    } catch (JSONException e) {
                    }
                }
                return view;
            }
        };
        adapter.setDropDownViewResource(R.layout.spinner_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //todo
                if (setting_status == true)
                {
                    spinner.setSelection(position);
                    updateTaskAreaEquipment(position);
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        return spinner;
    }

    public JSONObject getCompleteXMInLocal(String equipmentId, String areaId, String taskId, String itemStatus) {
        JSONObject completeXmInfo = null;
        TaskDbHelper taskDbHelper = new TaskDbHelper(TaskCheckActivity.this);
        SQLiteDatabase db = taskDbHelper.getReadableDatabase();
//        String query = "time = '" + HttpUtil.getCurrentDateString() +
//                "' and user_id = '" + LocalStorage.getUserXtm(TaskCheckActivity.this)
//                + "'" + " and task_id = '" + taskId + "'" + " and area_id = '" + areaId + "'" + " and equipment_id = '" + equipmentId + "'"
//                + " and equipmentStatus = '" + itemStatus + "'";
        String query = "user_id = '" + LocalStorage.getUserXtm(TaskCheckActivity.this)
                + "'" + " and task_id = '" + taskId + "'" + " and area_id = '" + areaId + "'" + " and equipment_id = '" + equipmentId + "'"
                + " and equipmentStatus = '" + itemStatus + "'";
        String[] columns = {"data"};
        Cursor cursor = null;
        try {
            cursor = db.query("complete_task", columns, query, null, null, null, null);
            while (cursor.moveToNext()) {
                if (cursor.getColumnIndex("data") > -1) {
                    String data = cursor.getString(cursor.getColumnIndex("data"));
                    try {
                        completeXmInfo = new JSONObject(data);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

            }

        } catch (SQLException e) {
        }
        //关闭数据库
        db.close();
        return completeXmInfo;
    }

    public Spinner initTaskStatusSpinner() {
        final Spinner spinner = (Spinner) findViewById(R.id.select_status);
        spinner.setPrompt("选择状态");
//        spinner.setSelection(0);
        ArrayAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mTaskStatus);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                spinner.setSelection(position);
                mItemStatus = mTaskStatusSpinner.getSelectedItem().toString();
                // TODO: 17/12/27 更新设备状态
//                mTaskEquipments = getAllEquipmentNames(mCurrentAreaData);
                int index = mTaskEquipmentNameSpinner.getSelectedItemPosition();
                try {
                    mTaskEquipments.set(index,mCurrentEquipment.getString("description")+" - "+mItemStatus);
                    mCurrentCompleteEquipmentInfo = getCompleteXMInfo(mCurrentEquipment.getString("xtm"), mCurrentAreaData.getString("xtm"), mCurrentTaskData.getString("xtm"),index,mItemStatus);
                    mCurrentCompleteEquipmentInfo.put("sbzt",mItemStatus);
//                    Log.e("修改状态后的mCurrentCompleteEquipmentInfo",mCurrentCompleteEquipmentInfo.toString());
//                    Log.e("jumpToNextEquipment","========index=========="+index);
//                    Log.e("jumpToNextEquipment","========index=========="+mCurrentCompleteEquipmentInfo.toString());
                    mAreaAllCompleteEquipment.put(index,mCurrentCompleteEquipmentInfo);
                    saveTempCheckTaskInLocal();
                }catch (JSONException e)
                {

                }
                ArrayAdapter<String> adapter = (ArrayAdapter<String>)mTaskEquipmentNameSpinner.getAdapter();
                adapter.notifyDataSetChanged();
//                Log.e("jumpToNextEquipment","========选择状态==========");
//                Log.e("jumpToNextEquipment","========选择状态=========="+mTaskEquipmentNameSpinner.getSelectedItemPosition());
                updateListView(mTaskEquipmentNameSpinner.getSelectedItemPosition());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        return spinner;
    }


    public JSONObject getXMInfo(int i) {
        JSONObject xmInfo = new JSONObject();

        try {
            xmInfo = mCurrentCompleteEquipmentInfo.getJSONArray("xmdata").getJSONObject(i);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return xmInfo;
    }

//    public JSONObject getCompleteXMInfo(String equipmentId, String areaId, String taskId) {
//        JSONObject completeEquipmentInfo = new JSONObject();
//        String key = "allCompleteCheckedTask_"+ LocalStorage.getUserXtm(TaskCheckActivity.this);
//        JSONObject allCompleteCheckedTask = LocalStorage.getObject(TaskCheckActivity.this, key);
//
//        String todayDate = HttpUtil.getCurrentDateString();
//
//        try {
//            JSONArray todayTask = allCompleteCheckedTask.getJSONArray(todayDate);
//            boolean status = false;
//            for (int i = 0; i < todayTask.length(); i++) {
//                String qysbxtm = todayTask.getJSONObject(i).getString("qysbxtm");
//                String rwxtm = todayTask.getJSONObject(i).getString("rwxtm");
//                String xdjqyxtm = todayTask.getJSONObject(i).getString("xdjqyxtm");
//
//                if (qysbxtm.equals(equipmentId) && rwxtm.equals(taskId) && xdjqyxtm.equals(areaId)) {
//                    completeEquipmentInfo = todayTask.getJSONObject(i);
//                    status = true;
//                    break;
//                }
//            }
//            if(!status){
//                completeEquipmentInfo = initRecodeEquipmentInfo();
//            }
//
//
//        } catch (JSONException e) {
//            completeEquipmentInfo = initRecodeEquipmentInfo();
//            e.printStackTrace();
//        }
//        return completeEquipmentInfo;
//    }

    public JSONArray updateCompleteCheckTask(JSONArray todayCheckTask, JSONObject uploadEquipmentData) {
        boolean status = false;
        for (int i = 0; i < todayCheckTask.length(); i++) {
            try {
                String qysbxtm = todayCheckTask.getJSONObject(i).getString("qysbxtm");
                String rwxtm = todayCheckTask.getJSONObject(i).getString("rwxtm");
                String xdjqyxtm = todayCheckTask.getJSONObject(i).getString("xdjqyxtm");
                if (qysbxtm.equals(uploadEquipmentData.getString("qysbxtm")) && rwxtm.equals(uploadEquipmentData.getString("rwxtm")) && xdjqyxtm.equals(uploadEquipmentData.getString("xdjqyxtm"))) {
                    todayCheckTask.put(i, uploadEquipmentData);
                    status = true;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (!status) {
            todayCheckTask.put(uploadEquipmentData);
        }
        return todayCheckTask;

    }

    public void saveCompleteCheckInLocal(JSONObject uploadEquipmentData) {
        String key = "allCompleteCheckedTask_" + LocalStorage.getUserXtm(TaskCheckActivity.this);
        JSONObject allCompleteCheckedTask = LocalStorage.getObject(TaskCheckActivity.this, key);
        JSONArray todayCompleteTask = new JSONArray();
        try {
            todayCompleteTask = allCompleteCheckedTask.getJSONArray(HttpUtil.getCurrentDateString());
        } catch (JSONException e) {

        }

        try {
            todayCompleteTask = updateCompleteCheckTask(todayCompleteTask, uploadEquipmentData);
            allCompleteCheckedTask.put(HttpUtil.getCurrentDateString(), todayCompleteTask);
            LocalStorage.saveObject(TaskCheckActivity.this, key, allCompleteCheckedTask);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    public JSONObject initRecodeEquipmentInfo() {
        JSONObject uploadEquipmentData = new JSONObject();
        try {
            uploadEquipmentData.put("xjr", mUserName);
            uploadEquipmentData.put("sbms", mCurrentEquipment.getString("description"));
            uploadEquipmentData.put("qysbxtm", mCurrentEquipment.getString("xtm")); //shebi id
            uploadEquipmentData.put("sbzt", mCurrentEquipment.getString("sbzt"));
            uploadEquipmentData.put("rwms", mCurrentTaskData.getString("description"));
            uploadEquipmentData.put("rwxtm", mCurrentTaskData.getString("xtm")); //renwu id
            uploadEquipmentData.put("qyms", mCurrentAreaData.getString("description"));
            uploadEquipmentData.put("xdjqyxtm", mCurrentAreaData.getString("xtm")); //quyu id
            uploadEquipmentData.put("smqyms", mScanBarcodeResult);
            uploadEquipmentData.put("smsj", mScanBarcodeTime);
//            uploadEquipmentData.put("date", getTimeString(new Date()));
            JSONArray xmInfo = new JSONArray();
            JSONArray xmInfoBZ = mCurrentEquipment.getJSONArray("data");
            for (int i = 0; i < xmInfoBZ.length(); i++) {

                if (xmInfoBZ.getJSONObject(i).getString("qtd").contains(mItemStatus)){
                    String cdjg = "";
                    String sfycd = "0";
                    if (xmInfoBZ.getJSONObject(i).getString("cdlx").equals("GC")
                            && xmInfoBZ.getJSONObject(i).getString("jgzmr").equals("1")) {
                        JSONArray cdjgzlb = xmInfoBZ.getJSONObject(i).getJSONArray("cdjgzlb");
                        cdjg = cdjgzlb.getJSONObject(0).getString("sfmrx").equals("1") ? cdjgzlb.getJSONObject(0).getString("z") : cdjgzlb.getJSONObject(1).getString("z");
                        sfycd = cdjgzlb.getJSONObject(0).getString("sfmrx").equals("1") ? cdjgzlb.getJSONObject(0).getString("sfyc") : cdjgzlb.getJSONObject(1).getString("sfyc");
                    }
                    JSONObject info = new JSONObject();
                    info.put("cdjg", cdjg);
                    info.put("equipment_code", mCurrentEquipment.getString("equipment_code"));
                    info.put("isqx", "0");
                    info.put("sbxt", mTaskAreaNamesSpinner.getSelectedItem().toString());
                    info.put("sfgld", "");
                    info.put("sfycd", sfycd);
                    info.put("xmms", xmInfoBZ.getJSONObject(i).getString("description"));
                    info.put("xmxtm", xmInfoBZ.getJSONObject(i).getString("xtm"));
                    xmInfo.put(info);
                }

            }
            uploadEquipmentData.put("xmdata", xmInfo);
        } catch (JSONException e) {
            Log.e("JSONException e", e.toString());
        }
        return uploadEquipmentData;
    }

    public void setCheckboxChanged(int position, boolean isChecked, String key) {
        View itemView = mCheckInfoListView.getChildAt(position - mCheckInfoListView.getFirstVisiblePosition());
        JSONObject xmInfo;
        try {
            xmInfo = mCurrentCompleteEquipmentInfo.getJSONArray("xmdata").getJSONObject(position);
        } catch (JSONException e) {
            xmInfo = initXMInfo(position);
            e.printStackTrace();
        }
        CheckBox passCheck = (CheckBox) itemView.findViewById(R.id.pass_id);
        CheckBox dispassCheck = (CheckBox) itemView.findViewById(R.id.dispass_id);
        passCheck.setChecked(false);
        dispassCheck.setChecked(false);
        if (key.equals("dispass")) {
            dispassCheck.setChecked(isChecked);
            passCheck.setChecked(!isChecked);
            try {
                xmInfo.put("cdjg", isChecked ? dispassCheck.getText() : passCheck.getText());
                xmInfo.put("sfycd", isChecked ? "1" : "0");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (key.equals("pass")) {
            dispassCheck.setChecked(!isChecked);
            passCheck.setChecked(isChecked);
            try {
                xmInfo.put("cdjg", isChecked ? passCheck.getText() : dispassCheck.getText());
                xmInfo.put("sfycd", isChecked ? "0" : "1");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
//        if (key.equals("faceBug")) {
//            try {
//                xmInfo.put("sfycd", isChecked ? "1" : "0");
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
//        }
        try {
            mCurrentCompleteEquipmentInfo.getJSONArray("xmdata").put(position, xmInfo);
            mAreaAllCompleteEquipment.put(mTaskEquipmentNameSpinner.getSelectedItemPosition(),mCurrentCompleteEquipmentInfo);
            saveTempCheckTaskInLocal();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void updateCheckValue(EditText editText,int position, String value) {

        JSONObject xmInfo;
        try {
            xmInfo = mCurrentCompleteEquipmentInfo.getJSONArray("xmdata").getJSONObject(position);

        } catch (JSONException e) {
            xmInfo = initXMInfo(position);
        }
        Log.e("xmInfo",xmInfo.toString());
        try {
            xmInfo.put("cdjg", value);
            double test_value = Double.parseDouble(value);
            JSONArray arrCurrentStatusEquipments = new JSONArray();
            for (int i = 0; i < mCurrentEquipment.getJSONArray("data").length(); i ++)
            {
                JSONObject equipment = mCurrentEquipment.getJSONArray("data").getJSONObject(i);
                if (equipment.getString("qtd").contains(mItemStatus))
                {
                    arrCurrentStatusEquipments.put(equipment);
                }
            }

            JSONObject standard_xminfo = arrCurrentStatusEquipments.getJSONObject(position);
            double sxz = Double.parseDouble(standard_xminfo.getString("sxz"));
            double xxz = Double.parseDouble(standard_xminfo.getString("xxz"));
            String sfycd = (test_value < xxz || test_value > sxz) ? "1" : "0";
            xmInfo.put("sfycd", sfycd);
            xmInfo.put("sxz", standard_xminfo.getString("sxz"));
            xmInfo.put("xxz", standard_xminfo.getString("xxz"));
            mCurrentCompleteEquipmentInfo.getJSONArray("xmdata").put(position, xmInfo);
            mAreaAllCompleteEquipment.put(mTaskEquipmentNameSpinner.getSelectedItemPosition(),mCurrentCompleteEquipmentInfo);
            saveTempCheckTaskInLocal();
            if (sfycd.equals("1"))
            {
                editText.setTextColor(Color.parseColor("#ff0000"));
            }
            else
            {
                editText.setTextColor(Color.parseColor("#000000"));
            }
        } catch (JSONException e) {
            Log.e("hhhhhh",e.getMessage());
        }
    }

    public void updateDefactBug(int position, JSONObject defectInfo) {
        JSONObject xmInfo;
        try {
            xmInfo = mCurrentCompleteEquipmentInfo.getJSONArray("xmdata").getJSONObject(position);
        } catch (JSONException e) {
            xmInfo = initXMInfo(position);
            e.printStackTrace();
        }

        try {
            xmInfo.put("lxzy", defectInfo.getString("lxzy"));
            xmInfo.put("lxr", defectInfo.getString("lxr"));
            xmInfo.put("qxdj", defectInfo.getString("qxdj"));
            xmInfo.put("qxms", defectInfo.getString("qxms"));
            xmInfo.put("jz", defectInfo.getString("jz"));
            xmInfo.put("isqx", defectInfo.getString("isqx"));
            xmInfo.put("equipment_code", defectInfo.getString("equipment_code"));
            xmInfo.put("sbxt", defectInfo.getString("sbxt"));
            mCurrentCompleteEquipmentInfo.getJSONArray("xmdata").put(position, xmInfo);
            mAreaAllCompleteEquipment.put(mTaskEquipmentNameSpinner.getSelectedItemPosition(),mCurrentCompleteEquipmentInfo);
            saveTempCheckTaskInLocal();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public JSONObject initXMInfo(int position) {
        JSONObject xmInfo = new JSONObject();
        try {
            JSONObject info = mCurrentEquipment.getJSONArray("data").getJSONObject(position);
            xmInfo.put("xmxtm", info.getString("xtm"));
            xmInfo.put("xmms", info.getString("description"));
            xmInfo.put("sfycd", "0");
            xmInfo.put("isqx", "0");
            xmInfo.put("equipment_code", mCurrentEquipment.getString("equipment_code"));
            xmInfo.put("sbxt", mTaskAreaNamesSpinner.getSelectedItem().toString());
            xmInfo.put("cdjg", "");
            xmInfo.put("sfgld", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return xmInfo;

    }

    public JSONObject getNewXMInfo(JSONObject xmInfo) {
        JSONObject newXMInfo = new JSONObject();
        try {
            newXMInfo.put("pk", xmInfo.getString("pk"));
            newXMInfo.put("cdjg", xmInfo.getString("cdjg"));
            newXMInfo.put("xmxtm", xmInfo.getString("xmxtm"));
            newXMInfo.put("xmms", xmInfo.getString("xmms"));
            newXMInfo.put("sfgld", xmInfo.getString("sfgld"));
            newXMInfo.put("sfycd", xmInfo.getString("sfycd"));
            newXMInfo.put("sbxt", xmInfo.getString("sbxt"));
            newXMInfo.put("isqx", xmInfo.getString("isqx"));
            newXMInfo.put("equipment_code", xmInfo.getString("equipment_code"));
            newXMInfo.put("jz", xmInfo.getString("jz"));

            newXMInfo.put("qxdj", xmInfo.getString("qxdj"));
            newXMInfo.put("qxms", xmInfo.getString("qxms"));
            newXMInfo.put("lxr", xmInfo.getString("lxr"));
            newXMInfo.put("lxzy", xmInfo.getString("lxzy"));

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return newXMInfo;

    }

    public void getHttpHeads() {

        TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        mDeviceToken = TelephonyMgr.getDeviceId();
//        WifiManager wm = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
//        mDeviceToken = wm.getConnectionInfo().getMacAddress();
        JSONObject User = LocalStorage.getObject(TaskCheckActivity.this, "User");
        mYhxtm = "";
        try {
            mYhxtm = User.getString("yhxtm");
            mUserName = User.getString("usernamecn");
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }


    public JSONArray getTaskListTest(String bc, JSONArray taskList) {
        TaskDbHelper taskDbHelper = new TaskDbHelper(TaskCheckActivity.this);
        SQLiteDatabase db = taskDbHelper.getReadableDatabase();
//        String query = "time = '" + HttpUtil.getCurrentDateString() +
//                "' and user_id = '" + LocalStorage.getUserXtm(TaskCheckActivity.this)
//                + "'" + " and bc = '" + bc + "'";
        String query = "start_date <= '" + HttpUtil.getCurrentDateString() +
                "' and end_date >= '"  + HttpUtil.getCurrentDateString() +
                "' and user_id = '" + LocalStorage.getUserXtm(TaskCheckActivity.this)
                + "'" + " and bc = '" + bc + "'";
        //开始时间<=HttpUtil.getCurrentDateString()<=结束时间
        String[] columns = {"data", "task_id", "is_complete"};
        Cursor cursor = null;
        try {
            cursor = db.query("task", columns, query, null, null, null, null);
            while (cursor.moveToNext()) {

                JSONObject task = new JSONObject();
                if (cursor.getColumnIndex("data") > -1) {
                    String data = cursor.getString(cursor.getColumnIndex("data"));
                    String is_complete = cursor.getString(cursor.getColumnIndex("is_complete"));
                    try {
                        task = new JSONObject(data);
                        task.put("is_complete", is_complete);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                taskList.put(task);
            }
        } catch (SQLException e) {
        }
        //关闭数据库
        db.close();

        return taskList;
    }

    public JSONArray sortWithComplete(JSONArray allData, boolean isCompleted) {
        JSONArray completeTask = new JSONArray();
        for (int i = 0; i < allData.length(); i++) {
            try {
                JSONObject task = allData.getJSONObject(i);
                if (task.getString("is_complete").equals("1") == isCompleted) {
                    completeTask.put(task);
                }
            } catch (Exception e) {

            }
        }
        return completeTask;
    }

    public JSONArray sortWithStartTime(JSONArray allData) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d1;
        Date d2;
        JSONObject temp_r = new JSONObject();
        for (int i = 0; i < allData.length() - 1; i++) {
            for (int j = i + 1; j < allData.length(); j++) {
                ParsePosition pos1 = new ParsePosition(0);
                ParsePosition pos2 = new ParsePosition(0);
                try {
                    d1 = sdf.parse(allData.getJSONObject(i).getString("kssj"), pos1);
                    d2 = sdf.parse(allData.getJSONObject(j).getString("kssj"), pos2);
                    if (d1.after(d2)) {//如果队前日期靠后，调换顺序
                        temp_r = allData.getJSONObject(i);
                        allData.put(i, allData.getJSONObject(j));
                        allData.put(j, temp_r);
                    }
                } catch (Exception e) {

                }

            }
        }
        return allData;
    }

    JSONArray getAllSortTaskArray(JSONArray unCompletedTask, JSONArray completeTask) {
        for (int i = 0; i < completeTask.length(); i++) {
            try {
                unCompletedTask.put(completeTask.getJSONObject(i));
            } catch (Exception e) {

            }

        }
        return unCompletedTask;
    }

    public JSONObject getAllTaskList() {
        JSONObject HH = new JSONObject();
        JSONArray mAllTaskList = new JSONArray();
        mAllTaskList = getTaskListTest("后夜班", mAllTaskList);
        mAllTaskList = getTaskListTest("白班", mAllTaskList);
        mAllTaskList = getTaskListTest("前夜班", mAllTaskList);
        mAllTaskList = getTaskListTest("燃料夜班", mAllTaskList);
        mAllTaskList = getTaskListTest("燃料白班", mAllTaskList);


        JSONArray unCompletedTask = sortWithComplete(mAllTaskList, false);
        JSONArray completeTask = sortWithComplete(mAllTaskList, true);
        unCompletedTask = sortWithStartTime(unCompletedTask);
        completeTask = sortWithStartTime(completeTask);
        unCompletedTask = getAllSortTaskArray(unCompletedTask, completeTask);

        try {
            HH.put("data", unCompletedTask);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return HH;
    }

    public JSONObject getCompleteXMInfo(String equipmentId, String areaId, String taskId, Integer position, String sbzt) {
//        Log.e("=========getCompleteXMInfo===","======="+equipmentId+"==============="+areaId+"=========="+taskId);
        JSONObject completeXmInfo = new JSONObject();
        TaskDbHelper taskDbHelper = new TaskDbHelper(TaskCheckActivity.this);
        SQLiteDatabase db = taskDbHelper.getReadableDatabase();
//        String query = "time = '" + HttpUtil.getCurrentDateString() +
//                "' and user_id = '" + LocalStorage.getUserXtm(TaskCheckActivity.this)
//                + "'" + " and task_id = '" + taskId + "'" + " and area_id = '" + areaId + "'" + " and equipment_id = '" + equipmentId + "'"
//                + " and equipmentStatus = '" + mItemStatus + "'";
        String query = "user_id = '" + LocalStorage.getUserXtm(TaskCheckActivity.this)
                + "'" + " and task_id = '" + taskId + "'" + " and area_id = '" + areaId + "'" + " and equipment_id = '" + equipmentId + "'"
                + " and equipmentStatus = '" + mItemStatus + "'";
        String[] columns = {"data"};
        Cursor cursor = null;
        try {
            cursor = db.query("complete_task", columns, query, null, null, null, null);
            if (cursor.getCount() == 0) {
//                Log.e("=========getCount===","====initRecodeEquipmentInfo===");
//                Log.e("=========position===","====initRecodeEquipmentInfo==="+position+"================"+sbzt);
                if(position>-1){

                    try {
                        completeXmInfo =  mAreaAllCompleteEquipment.getJSONObject(position);
                        if(!completeXmInfo.getString("sbzt").equals(sbzt)){
//                            Log.e("=========getCount===","====completeXmInfo===");
                            completeXmInfo = initRecodeEquipmentInfo();
                        }
                    } catch (JSONException e) {
//                        Log.e("=========getCount===","===JSONException====");
                        completeXmInfo = initRecodeEquipmentInfo();
                        e.printStackTrace();
                    }
                }

            }
            while (cursor.moveToNext()) {
                if (cursor.getColumnIndex("data") > -1) {
                    String data = cursor.getString(cursor.getColumnIndex("data"));
                    try {
                        completeXmInfo = new JSONObject(data);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

            }

        } catch (SQLException e) {
        }
        //关闭数据库
        db.close();
        return completeXmInfo;
    }

    public void saveCompleteXmInfo(JSONObject uploadEquipmentData,JSONArray types) {
        TaskDbHelper taskDbHelper = new TaskDbHelper(TaskCheckActivity.this);
        SQLiteDatabase db = taskDbHelper.getWritableDatabase();
        String query = null;
        try {
//            query = "time = '" + HttpUtil.getCurrentDateString() +
//                    "' and user_id = '" + LocalStorage.getUserXtm(TaskCheckActivity.this)
//                    + "'" + " and task_id = '" + uploadEquipmentData.getString("rwxtm") + "'" + " and area_id = '" + uploadEquipmentData.getString("xdjqyxtm") + "'"
//                    + " and equipment_id = '" + uploadEquipmentData.getString("qysbxtm") + "'" + " and equipmentStatus = '" + uploadEquipmentData.getString("sbzt") + "'";
            query = "user_id = '" + LocalStorage.getUserXtm(TaskCheckActivity.this)
                    + "'" + " and task_id = '" + uploadEquipmentData.getString("rwxtm") + "'" + " and area_id = '" + uploadEquipmentData.getString("xdjqyxtm") + "'"
                    + " and equipment_id = '" + uploadEquipmentData.getString("qysbxtm") + "'" + " and equipmentStatus = '" + uploadEquipmentData.getString("sbzt") + "'";

        } catch (JSONException e) {
            e.printStackTrace();
        }
        db.delete("complete_task", query, null);
        ContentValues cv = new ContentValues();
        try {
            cv.put("task_id", uploadEquipmentData.getString("rwxtm"));
            cv.put("area_id", uploadEquipmentData.getString("xdjqyxtm"));
            cv.put("user_id", LocalStorage.getUserXtm(TaskCheckActivity.this));
            cv.put("data", uploadEquipmentData.toString());
            cv.put("isUploadSuccess", uploadEquipmentData.getString("isUploadSuccess"));
            cv.put("time", HttpUtil.getCurrentDateString());
            cv.put("equipment_id", uploadEquipmentData.getString("qysbxtm"));
            cv.put("equipmentStatus", uploadEquipmentData.getString("sbzt"));
            cv.put("task_info_type",types.toString());
            db.insert("complete_task", null, cv);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        db.close();

    }

    public void saveTempCompleteXmInfo(JSONObject uploadEquipmentData,JSONArray types) {
        TaskDbHelper taskDbHelper = new TaskDbHelper(TaskCheckActivity.this);
        SQLiteDatabase db = taskDbHelper.getWritableDatabase();
        String query = null;
        try {
//            query = "time = '" + HttpUtil.getCurrentDateString() +
//                    "' and user_id = '" + LocalStorage.getUserXtm(TaskCheckActivity.this)
//                    + "'" + " and task_id = '" + uploadEquipmentData.getString("rwxtm") + "'" + " and area_id = '" + uploadEquipmentData.getString("xdjqyxtm") + "'"
//                    + " and equipment_id = '" + uploadEquipmentData.getString("qysbxtm") + "'" + " and equipmentStatus = '" + uploadEquipmentData.getString("sbzt") + "'";
            query = "user_id = '" + LocalStorage.getUserXtm(TaskCheckActivity.this)
                    + "'" + " and task_id = '" + uploadEquipmentData.getString("rwxtm") + "'" + " and area_id = '" + uploadEquipmentData.getString("xdjqyxtm") + "'"
                    + " and equipment_id = '" + uploadEquipmentData.getString("qysbxtm") + "'" + " and equipmentStatus = '" + uploadEquipmentData.getString("sbzt") + "'";
        } catch (JSONException e) {
            e.printStackTrace();
        }

        db.delete("complete_task", query, null);
        ContentValues cv = new ContentValues();
        try {
            String isUpload;
            try{
                isUpload = uploadEquipmentData.getString("isUploadSuccess");
            }catch (JSONException e)
            {
                isUpload = "";
            }
//            Log.e("isUploadSuccess============",isUpload + "============" + uploadEquipmentData.getString("qysbxtm"));
            cv.put("task_id", uploadEquipmentData.getString("rwxtm"));
            cv.put("area_id", uploadEquipmentData.getString("xdjqyxtm"));
            cv.put("user_id", LocalStorage.getUserXtm(TaskCheckActivity.this));
            cv.put("data", uploadEquipmentData.toString());
            cv.put("isUploadSuccess", isUpload);
            cv.put("time", HttpUtil.getCurrentDateString());
            cv.put("equipment_id", uploadEquipmentData.getString("qysbxtm"));
            cv.put("equipmentStatus", uploadEquipmentData.getString("sbzt"));
            cv.put("task_info_type",types.toString());
            db.insert("complete_task", null, cv);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        db.close();
    }


}
